<script setup lang="ts">
import {ref, reactive, PropType} from 'vue'
import {FormRules, ElMessage} from 'element-plus'
import {FromItem} from '@/components/dFrom/dFrom'
import {DialogType} from '@/api/config'
import dDialog from '@/components/dDialog/dDialog.vue'
import dFrom from '@/components/dFrom/dFrom.vue'
import {
  ChineseLetter,
  NotLeadingAndTrailingSpaces,
  PhoneNumber
} from '@/util/common'
import {getHierarchicList} from '@/api/baseSetting/institutionalData'
import {
  saveTeamInfor,
  TeamList
} from '@/api/publicHealthExamination/communitySettings'
//是否显示
const props = defineProps({
  //显示
  showDialog: {
    type: Boolean,
    required: true
  },
  //弹窗类型
  dialogType: {
    type: String as PropType<DialogType>,
    required: true
  },
  //数据
  communityData: {
    type: Object as PropType<TeamList>,
    required: true
  }
})

const emits = defineEmits(['close'])

// 弹窗标题定义
const title = ref(props.dialogType === 'add' ? '新增社区' : '编辑社区')

//信息
const formData: TeamList = reactive(props.communityData)

// 显示加载状态
const showSaveLoading = ref(false)

// 表单规则
const rules = reactive<FormRules>({
  name: [
    {required: true, message: '请输入社区名称', trigger: ['change', 'blur']},
    {
      message: '长度应不超过100个字符',
      max: 100,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入汉字、字母、数字、字符，首尾不能为空',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ],
  leader: [
    {
      message: '长度应不超过20个字符',
      max: 20,
      trigger: ['change', 'blur']
    },
    {
      message: '应输入汉字、字母',
      pattern: ChineseLetter,
      trigger: ['change', 'blur']
    }
  ],
  phone: [
    {
      message: '长度应不超过11个字符',
      max: 11,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入正确的手机号码',
      pattern: PhoneNumber,
      trigger: ['change', 'blur']
    }
  ],
  districtArr: [
    {required: true, message: '请选择地址', trigger: ['change', 'blur']}
  ],
  address: [
    {required: true, message: '请输入详细地址', trigger: ['change', 'blur']},
    {
      message: '请输入汉字、字母、数字、字符，首尾不能为空',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    },
    {
      message: '长度应不超过100个字符',
      max: 100,
      trigger: ['change', 'blur']
    }
  ]
})

//表单项
const fromItems = ref<Array<FromItem>>([
  {
    label: '社区名称',
    placeholder: '请输入社区名称',
    prop: 'name',
    type: 'input'
  },
  {
    label: '负责人',
    placeholder: '请输入负责人姓名',
    prop: 'leader',
    type: 'input'
  },
  {
    label: '联系电话',
    placeholder: '请输入负责人联系电话',
    prop: 'phone',
    type: 'input'
  },
  {
    label: '地址',
    placeholder: '请选择省/市/区',
    prop: 'districtArr',
    type: 'slot',
    slotName: 'districtArr'
  },
  {
    label: '详细地址',
    placeholder: '示例：街道、栋数',
    prop: 'address',
    type: 'input',
    style: {'grid-column': '1/3'}
  }
])

//表单清除控制
const resetFieldsFlag = ref(false)

const validateFlag = ref(false)

// 确认按钮
const onConfirm = () => {
  validateFlag.value = !validateFlag.value
}

//关闭
const onClose = () => {
  emits('close')
  //关闭后清除表单数据以及表单验证数据 可根据具体业务自行调整
  resetFieldsFlag.value = !resetFieldsFlag.value
}

//取消按钮
const onCancel = () => {
  onClose()
}

//表单验证通过事件
const onSubmit = () => {
  showSaveLoading.value = true
  const params: Partial<TeamList> = {
    id: formData.id,
    name: formData.name,
    leader: formData.leader,
    phone: formData.phone,
    address: formData.address
  }
  params.districtCode = formData.districtArr?.length
    ? formData.districtArr[formData.districtArr.length - 1]
    : ''
  saveTeamInfor(params)
    .then(() => {
      showSaveLoading.value = false
      ElMessage.success('保存成功！')
      emits('close')
    })
    .catch((error) => {
      showSaveLoading.value = false
      console.warn(error)
    })
}

/**
 * @description: 行政地址选择器
 * @return {*}
 */
const cascaderProps = {
  checkStrictly: true,
  lazy: true,
  lazyLoad(node, resolve) {
    const {level, data} = node
    getHierarchicList({parentCode: data.value}).then((res) => {
      const arr: Array<{value: string; label: string; leaf: boolean}> = []
      if (res.data.data && res.data.data.length) {
        res.data.data.forEach((a) => {
          arr.push({
            value: a.districtCode,
            label: a.districtName,
            leaf: level >= 2
          })
        })
      } else {
        arr.push({label: '暂无', value: '', leaf: true})
      }
      resolve(arr)
    })
  }
}
</script>

<template>
  <d-dialog
    :title="title"
    :show-dialog="showDialog"
    :width="800"
    :show-save-loading="showSaveLoading"
    @cancel="onCancel"
    @confirm="onConfirm"
    @close="onClose"
  >
    <d-from
      label-position="right"
      :label-width="100"
      :reset-fields-flag="resetFieldsFlag"
      :validate-flag="validateFlag"
      :rules="rules"
      method="post"
      :form-data="formData"
      :form-items="fromItems"
      :form-line-num="2"
      @submit="onSubmit"
    >
      <template #districtArr>
        <el-cascader
          v-model="formData.districtArr"
          clearable
          placeholder="请选择省/市/区"
          :props="cascaderProps"
          style="width: 100%"
        />
      </template>
    </d-from>
  </d-dialog>
</template>
<style scoped></style>
